<template>
  <view class="body">
    <up-steps :current="state.steps" activeColor="#00D1B6" inactiveColor="#999999">
      <up-steps-item title="基本情况"></up-steps-item>
      <up-steps-item title="患病情况"></up-steps-item>
      <up-steps-item title="生活方式"></up-steps-item>
      <up-steps-item title="补充信息"></up-steps-item>
    </up-steps>
    <scroll-view
      v-if="state.steps == 1 || state.steps == 2"
      class="scroll-X"
      @scroll="scrollX"
      :scroll-with-animation="true"
      :scroll-left="scrollLeft"
      scroll-x="true"
    >
      <view class="tabList">
        <view
          :class="['item', state.tabActive == index ? 'on' : '']"
          v-for="(item, index) in state.steps == 1 ? state.tabList : state.tabList2"
          :key="index"
          @tap="tabFun(index)"
        >
          <text class="text">{{ item }}</text>
        </view>
      </view>
    </scroll-view>
    <view :class="['wrap', state.steps == 1 || state.steps == 2 ? 'small_height' : '']">
      <view v-if="state.steps == 0" class="list">
        <view
          v-for="(item, index) of state.questionList['基本情况']"
          :key="index"
          class="list_item"
        >
          <view class="list_item_title">
            <view class="nums"
              ><text style="color: #00d1b6">{{ index + 1 }}</text
              >/{{ state.questionList['基本情况']?.length }}</view
            >
            <view :class="['tag', item.questionType == '单选' ? '' : 'check']">{{
              item.questionType
            }}</view>
            <view class="title"
              >{{ item.questionName }}</view
            >
          </view>
          <view class="remark">
            {{ item.remark }}
          </view>
          <view class="answer">
            <view
              v-for="(i, idx) of item.options"
              :key="idx"
              :class="['answer_item', i.check ? 'on' : '']"
            >
              {{ i.label }}
            </view>
          </view>
        </view>
      </view>
      <view v-if="state.steps == 1" class="list">
        <scroll-view
          :scroll-top="scrollTop"
          @scroll="scroll"
          :scroll-with-animation="true"
          class="scroll-Y"
          scroll-y="true"
        >
          <view
            v-for="(item, index) of state.questionList['患病情况']"
            :key="index"
            :class="['list_item', 'list_item' + index]"
          >
            <view class="list_item_title">
              <view class="nums"
                ><text style="color: #00d1b6">{{ index + 1 }}</text
                >/{{ state.questionList['患病情况']?.length }}</view
              >
              <view :class="['tag', item.questionType == '单选' ? '' : 'check']">{{
                item.questionType
              }}</view>
              <view class="title"
                >{{ item.questionName }}</view
              >
            </view>
            <view class="remark">
              {{ item.remark }}
            </view>
            <view class="answer">
              <view
                v-for="(i, idx) of item.options"
                :key="idx"
                :class="['answer_item', i.check ? 'on' : '']"
              >
                {{ i.label }}
              </view>
            </view>
          </view>
        </scroll-view>
      </view>
      <view v-if="state.steps == 2">
        <scroll-view
          :scroll-top="scrollTop"
          @scroll="scroll"
          :scroll-with-animation="true"
          class="scroll-Y"
          scroll-y="true"
        >
          <view
            v-for="(arr_item, arr_index) of lifeList"
            :key="arr_index"
            :class="['list', 'list' + arr_index]"
          >
            <view class="list_title">
              {{
                arr_index == 0
                  ? '膳食摄入'
                  : arr_index == 1
                  ? '饮食习惯'
                  : arr_index == 2
                  ? '运动锻炼'
                  : arr_index == 3
                  ? '吸烟情况'
                  : '饮酒情况'
              }}
            </view>
            <image
              class="img_bg"
              src="https://ainengli.hzjrsw.com/jkhx/questionTitleBg.png"
            ></image>
            <view v-for="(item, index) of arr_item" :key="index" class="list_item">
              <view class="list_item_title">
                <view class="nums"
                  ><text style="color: #00d1b6">{{ index + 1 }}</text
                  >/{{ arr_item?.length }}</view
                >
                <view :class="['tag', item.questionType == '单选' ? '' : 'check']">{{
                  item.questionType
                }}</view>
                <view class="title"
                  >{{ item.questionName }}</view
                >
              </view>
              <view class="remark">
                {{ item.remark }}
              </view>
              <view class="answer">
                <view
                  v-for="(i, idx) of item.options"
                  :key="idx"
                  :class="['answer_item', i.check ? 'on' : '']"
                >
                  {{ i.label }}
                </view>
              </view>
            </view>
          </view>
        </scroll-view>
      </view>
      <view v-if="state.steps == 3" class="list">
        <view
          v-for="(item, index) of state.questionList['补充信息']"
          :key="index"
          class="list_item"
        >
          <view class="list_item_title">
            <view class="nums"
              ><text style="color: #00d1b6">{{ index + 1 }}</text
              >/{{ state.questionList['补充信息']?.length }}</view
            >
            <view :class="['tag', item.questionType == '单选' ? '' : 'check']">{{
              item.questionType
            }}</view>
            <view class="title"
              >{{ item.questionName }}</view
            >
          </view>
          <view class="remark">
            {{ item.remark }}
          </view>
          <view class="answer">
            <view
              v-for="(i, idx) of item.options"
              :key="idx"
              :class="['answer_item', i.check ? 'on' : '']"
            >
              {{ i.label }}
            </view>
          </view>
        </view>
      </view>
    </view>
    <view class="fixed">
      <button v-if="state.steps != 0" class="pre_btn" @tap="prev()">上一页</button>
      <button v-if="state.steps != 3" class="next_btn" @tap="next()">下一页</button>
    </view>
  </view>
</template>

<script setup lang="ts">
import { reactive, ref, watch, nextTick } from 'vue'
import { scale_info_assess } from '@/api/questionaire'
import { onLoad, onShow } from '@dcloudio/uni-app'
import { debounce, throttle, deepCopy } from '@/utils/tools'
import store from '@/store'

const state = reactive({
  steps: 0,
  tabActive: 0,
  tabList: ['本人', '父亲', '母亲', '祖父母', '外祖父母'],
  tabList2: ['膳食摄入', '饮食习惯', '运动锻炼', '吸烟情况', '饮酒情况'],
  questionList: []
})
const lifeList = ref([])
const userInfo = ref({})

const scrollTop = ref(0)
const scrollLeft = ref(0)
const distanceArr = ref([])
let currentId = ''

onLoad((option) => {
  state.steps = option.index ? option.index : 0
  userInfo.value = JSON.parse(uni.getStorageSync('userInfo'))
  if (!currentId || currentId !== userInfo.value.patientInfo.empi) {
    currentId = deepCopy(userInfo.value.patientInfo.empi)
    // currentId = '74567895'
    init()
  }
})

watch(
  () => state.steps,
  (n, o) => {
    state.tabActive = 0
    scrollTop.value = 0
    if (n === 1) {
      distanceArr.value = []
      nextTick(() => {
        state.questionList['患病情况'].forEach(async (item, index) => {
          getHeight('.list_item' + index).then((height) => {
            distanceArr.value.push(height - 133)
          })
        })
      })
    }
    if (n === 2) {
      distanceArr.value = []
      nextTick(() => {
        lifeList.value.forEach(async (item, index) => {
          getHeight('.list' + index).then((height) => {
            distanceArr.value.push(height - 133)
          })
        })
      })
    }
  },
  { immediate: true }
)
watch(
  () => state.tabActive,
  (n, o) => {
    if (n === 3 || n === 4) {
      scrollLeft.value = 155
    } else {
      scrollLeft.value = 0
    }
  },
  { immediate: true, deep: true }
)

const init = () => {
  if (store.state.QUESTIONAIRE.length > 0) {
    let arr = store.state.QUESTIONAIRE
    // 生活方式列表lifeList
    lifeList.value.push(arr['膳食摄入'])
    lifeList.value.push(arr['饮食习惯'])
    lifeList.value.push(arr['运动锻炼'])
    lifeList.value.push(arr['吸烟情况'])
    lifeList.value.push(arr['饮酒情况'])
    state.questionList = arr
  } else {
    scale_info_assess({ empi: currentId, userId: userInfo.value.userId }).then((res) => {
      if (res.code === 0) {
        state.questionInfo = res.data
        let arr = JSON.parse(res.data.answers)
        // 生活方式列表lifeList
        lifeList.value.push(arr['膳食摄入'])
        lifeList.value.push(arr['饮食习惯'])
        lifeList.value.push(arr['运动锻炼'])
        lifeList.value.push(arr['吸烟情况'])
        lifeList.value.push(arr['饮酒情况'])
        for (let value in arr) {
          arr[value].forEach((val) => {
            // 格式化选项并添加是否选中状态
            val.options = JSON.parse(val.options)
            val.options.forEach((item) => {
              if (val.questionType == '单选') {
                if (item.value == val.chosen) {
                  item.check = true
                } else {
                  item.check = false
                }
              } else {
                if (val.chosen.includes(item.value)) {
                  item.check = true
                } else {
                  item.check = false
                }
              }
            })
          })
        }
        state.questionList = arr
      }
    })
  }
}
const tabFun = (index) => {
  // tab切换
  state.tabActive = index
  scrollTop.value = distanceArr.value[index] || 0
}

const getHeight = (str: string) => {
  return new Promise((resolve, reject) => {
    const query = uni.createSelectorQuery()
    query
      .select(str)
      .boundingClientRect((data) => {
        resolve(data.top)
      })
      .exec()
  })
}

const prev = () => {
  state.steps--
  scrollTop.value = 0
  state.tabActive = 0
  scrollLeft.value = 0
}
const next = () => {
  state.steps++
  scrollTop.value = 0
  state.tabActive = 0
  scrollLeft.value = 0
}
const scroll = (e) => {
  if (state.tabActive <= 0) {
    // 在未显示tab并且 currentTab <= 0时，防止uview ui抖动bug，设置默认复位值
    state.tabActive = 0
  }
  nextTick(() => {
    const length = distanceArr.value.length
    const index = distanceArr.value.findIndex((el) => el - e.detail.scrollTop > 8)
    // 当index  == -1 的时候，实际当前滚动的距离超出了最大值，也就是在最后一个tab显示的内容
    // 当index > 0 的时候，说明能在当前的scrollTop值找到，即index的前一位
    state.tabActive = index > 0 ? index - 1 : length - 1
    if (index == 0) {
      state.tabActive = 0
    }
  })
}
const scrollX = debounce((e) => {
  scrollLeft.value = e.detail.scrollLeft
}, 200)
</script>

<style lang="scss" scoped>
.body {
  height: 100%;
  // 步骤条样式
  ::v-deep .u-steps {
    height: 140rpx;
    align-items: center;
    background: #fff;
  }
  ::v-deep .uicon-checkmark {
    font-size: 24rpx !important;
  }
  ::v-deep .u-steps-item__wrapper__circle__text {
    // transform: translateY(-2rpx);
  }
  ::v-deep .u-steps-item__line {
    height: 1rpx !important;
  }
  ::v-deep .u-steps-item__content {
    margin: 0 !important;
    margin-top: 16rpx !important;
    .u-text__value {
      font-size: 28rpx !important;
    }
    .u-text__value--main {
      color: #00d1b6;
    }
    .u-text__value--content {
      color: #999;
    }
  }
  .scroll-X {
    margin: 30rpx 0 0;
    width: 100%;
    box-sizing: border-box;
    overflow-x: scroll;
    background: #f3f7f8;
    .tabList {
      white-space: nowrap;
      .item {
        display: inline-block;
        vertical-align: middle;
        padding: 0 30rpx;
        text-align: center;
        font-size: 28rpx;
        color: #222;
        position: relative;
        height: 64rpx;
        line-height: 64rpx;
        background: #fff;
        margin-left: 32rpx;
        border-radius: 32rpx;
        &:nth-last-child(1) {
          margin-right: 32rpx;
        }
        &.on {
          color: #fff;
          font-weight: 700;
          background: #00d1b6;
        }
      }
    }
  }
  .wrap {
    margin-top: 32rpx;
    padding: 32rpx;
    padding-top: 0;
    height: calc(100vh - 316rpx);
    overflow-y: scroll;
    .small_height {
      height: calc(100vh - 440rpx);
    }
    .scroll-Y {
      height: calc(100vh - 440rpx);
    }
    .list {
      position: relative;
      overflow: hidden;
    }
    .list_title {
      font-weight: 600;
      font-size: 32rpx;
      color: #ffffff;
      margin: 26rpx 28rpx 22rpx;
    }
    .img_bg {
      position: absolute;
      width: 686rpx;
      height: 208rpx;
      top: 0;
      left: 0;
      z-index: -1;
    }
    .list_item {
      margin-bottom: 24rpx;
      background: #ffffff;
      border-radius: 16rpx;
      padding: 32rpx;
      .list_item_title {
        display: flex;
        justify-content: flex-start;
        align-items: center;
        gap: 8rpx;
        .nums {
          font-weight: 500;
          font-size: 24rpx;
          color: #666666;
        }
        .tag {
          width: 80rpx;
          height: 40rpx;
          line-height: 40rpx;
          text-align: center;
          background: #02bcc3;
          border-radius: 4rpx;
          font-weight: 500;
          font-size: 24rpx;
          color: #ffffff;
        }
        .check {
          background: #5c8eff;
        }
        .title {
          width: 480rpx;
          font-weight: 500;
          font-size: 32rpx;
          color: #222222;
        }
      }
      .remark {
        font-weight: 400;
        font-size: 24rpx;
        color: #999999;
        margin-left: 8rpx;
        margin-top: 16rpx;
        text-align: justify;
      }
      .answer {
        display: flex;
        flex-wrap: wrap;
        gap: 16rpx;
        justify-content: space-between;
        margin-top: 32rpx;
        .answer_item {
          border-radius: 8rpx;
          padding: 16rpx 30rpx;
          text-align: left;
          width: 48%;
          font-weight: 400;
          font-size: 28rpx;
          color: #999999;
          background: #f5f5f5;
          border: 1rpx solid #fafafa;
          transform: rotateZ(360deg);
          box-sizing: border-box;
          &.on {
            background: rgba(0, 209, 182, 0.1);
            border-radius: 8rpx;
            border: 1rpx solid #00d1b6;
            font-weight: 500;
            font-size: 28rpx;
            color: #00d1b6;
          }
        }
      }
    }
  }
  .fixed {
    position: fixed;
    width: 100%;
    bottom: 0;
    left: 0;
    z-index: 10;
    padding: 24rpx 32rpx;
    padding-bottom: calc(24rpx + constant(safe-area-inset-bottom));
    padding-bottom: calc(24rpx + env(safe-area-inset-bottom));
    box-sizing: border-box;
    background: #ffffff;
    display: flex;
    justify-content: space-between;
    gap: 24rpx;
    .pre_btn {
      background: #ffffff;
      width: 100%;
      border-radius: 44rpx;
      font-weight: 500;
      font-size: 32rpx;
      border: 1rpx solid #00d1b6;
      color: #00d1b6;
    }
    .next_btn {
      width: 100%;
      background: #00d1b6;
      border-radius: 44rpx;
      font-weight: 500;
      font-size: 32rpx;
      color: #ffffff;
    }
  }
}
</style>
